<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 分公司印章管理 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card
          :bordered="false"
          style="padding-bottom: 5rem"
        >
          <title-name title="基本信息" />
          <custom-form
            :form-list="formList"
            :form="form"
            :edit-model="editModel == 0 ? 'V' : ''"
            @getOption="(name, e) => getOption(name, e)"
          >
            <!--参加人员-->
            <template #personIds>
              <a-tag
                v-for="person in form.personIds"
                :key="person.id"
                :closable="editModel != 0"
                color="#108ee9"
                @close="form.personIds = form.personIds.filter((item) => person.id !== item.id)"
              >
                {{ person.name }}
              </a-tag>
              <a-button
                v-if="editModel != 0"
                icon="plus"
                :class="{ ml12: form.personIds ? form.personIds.length > 0 : false }"
                @click="visible = true"
              >
                添加人员
              </a-button>
            </template>
            <!-- 附件上传 -->
            <template #fileList>
              <template v-if="editModel != 0">
                <l-table
                  :file-auto-loading="false"
                  business-code="UN09"
                  :upload-arrys.sync="form.fileList"
                />
                <div class="file_prompt">请上传公司与分公司签订的保管责任书</div>
              </template>
              <file-link
                v-else
                :file-list="form.fileList"
              />
            </template>
            <!-- 附件上传 成立或更名文件-->
            <template #fileTypeList>
              <template v-if="editModel != 0">
                <l-table
                  :file-auto-loading="false"
                  business-code="UN09"
                  :upload-arrys.sync="form.fileTypeList"
                />
                <div class="file_prompt">请上传成立或更名文件</div>
              </template>
              <file-link
                v-else
                :file-list="form.fileTypeList"
              />
            </template>
            <!-- 附件上传 -->
            <template #preserverFile>
              <template v-if="editModel != 0">
                <l-table
                  :file-auto-loading="false"
                  business-code="UN09"
                  :upload-arrys.sync="form.preserverFile"
                />
                <div class="file_prompt">请上传分公司与印章保管人签定的保管责任书</div>
              </template>
              <file-link
                v-else
                :file-list="form.preserverFile"
              />
            </template>
          </custom-form>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button
          v-if="editModel != 0"
          :loading="loadingSub"
          type="primary"
          class="button_right"
          @click="handleSubmit()"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="handleActiveClose"
        > 关闭 </a-button>
      </div>
    </a-form-model>
     
    <SelectPersonModal
      :persons="form.personIds"
      :visible.sync="visible"
    />
  </base-breadcrumb>
</template>

<script>
import { create, update, detail } from '@/api/office/sealManage/filialeSealManage' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSupevise from '@/components/Select/SelectSupevise'
import SelectUndertaking from '@/components/Select/SelectUndertaking'
import Selector from '@/components/Select/Selector'
import { getEmployeesList } from '@/api/commons.js'
import { getLabels } from '@/api/office/supervise.js'
import { getEmployees } from '@/api/businessAffairs/revenueAndCost'
import moment from 'moment'
import SelectDepart from '@/components/Select/SelectDepart.vue'
import SelectPersonModal from '@/components/SelectPersonModal'
import { getOrgManageList } from '@/api/system/system'

export default {
  extends: new BaseEditPage(),
  components: {
    SelectPersonModal
  },
  data() {
    let _this = this
    const validatorFileList = (rule, value, callback) => {
      let state = _this.form.fileList === undefined || _this.form.fileList.length === 0
      if (state && this.fileListStatus) {
        callback(new Error('请上传保管责任书'))
      } else {
        callback()
      }
    }
    return {
      loading: false, // 加载控件
      loadingSub: false, // 加载按钮
      fileListStatus: false,
      visible: false, //人员选择控件
      editModel: this.$route.query.editModel, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        unitName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.name,
        careDepartmentId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.deptId,
        // careId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).id,
        care: {
          key: JSON.parse(sessionStorage.getItem('ycloud-user_info')).id,
          label: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name
        },
        phone: JSON.parse(sessionStorage.getItem('ycloud-user_info')).employee.phone
      }, // 表单
      rules: {
        unitName: [{ required: true, message: '自动带出单位名称' }],
        title: [{ required: true, message: '请输入印章名称' }],
        careDepartmentId: [{ required: true, message: '请选择保管部门' }],
        care: [{ required: true, message: '请选择保管人' }],
        phone: [{ required: true, message: '请输入联系电话' }],
        sealStatusId: [{ required: true, message: '请选择印章状态' }],
        fileList: [{ required: true, validator: validatorFileList }],
        preserverFile: [
          {
            type: 'array',
            required: true,
            message: '请上传分公司与印章保管人签定的保管责任书',
            trigger: 'blur'
          }
        ]
      }, // 校验规则
      init: false, // 初始化控件
      formCode: '' // 形式选中项code
    }
  },
  computed: {
    formList() {
      return [
        {
          type: 'BaseInput',
          keyName: 'unitName',
          viewName: 'unitName',
          disabled: true,
          placeholder: '根据登录人获取',
          label: '单位名称'
        },
        {
          keyName: 'title',
          viewName: 'title',
          type: 'a-input',
          label: '印章名称',
          ellipsis: true
        },
        {
          keyName: 'careDepartmentId',
          viewName: 'careDepartmentName',
          label: '保管部门',
          type: SelectDepart,
          attr: {
            placeholder: '请选择保管部门'
          },
          ellipsis: true
        },
        {
          keyName: 'care',
          viewName: 'careName',
          label: '保管人',
          type: SelectSupevise,
          placeholder: '请选择保管人',
          attrs: {
            orgId: this.form.careDepartmentId,
            culEdu: true,
            labelInValue: true
          },
          ellipsis: true
        },
        {
          keyName: 'phone',
          viewName: 'phone',
          type: 'a-input',
          label: '联系电话',
          ellipsis: true
        },
        {
          type: Selector,
          keyName: 'sealStatusId',
          viewName: 'statusName',
          label: '印章状态',
          attrs: {
            selectType: '10',
            urlType: 'union',
            isDefault: true
          }
        },
        // {
        //   keyName: 'title',
        //   viewName: 'title',
        //   type: 'a-input',
        //   label: '其他状态',
        //   ellipsis: true,
        // },
        {
          slot: true,
          keyName: 'fileList',
          label: '保管责任书',
          span: 24
        },
        {
          slot: true,
          keyName: 'fileTypeList',
          label: '成立（更名）文件',
          span: 24
        },
        {
          slot: true,
          keyName: 'preserverFile',
          label: '保管人责任书',
          span: 24
        }
      ]
    }
  },
  watch: {
    'form.fileList'() {
      this.fileListStatus = true
      this.$refs.ruleForm.validate((e) => {})
    },
    // 监听附件实现附件校验
    'form.preserverFile'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('preserverFile')
        })
      }
    }
  },

  methods: {
    /**
     * 获取选中项
     */
    getOption(name, e) {
      if (e) {
        if (name === 'careId') {
          this.form.phone = e.phone
        }
      }
    },
    /**
     * 默认层级
     */
    handleLevel() {
      let levelCode = JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.code
      if (levelCode == 'PD') {
        return '项目部'
      } else if (levelCode == 'BC') {
        return '分公司'
      } else if (levelCode == 'CO') {
        return '公司'
      }
    },
    /**
     * 校验表单
     */
    handleSubmit() {
      // 提交表单
      this.fileListStatus = true
      console.log(this.form.fileList)
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          this.handleSubmitApi()
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    /**
     * 提交表单
     */
    handleSubmitApi() {
      let that = this
      let api = [update, create][that.editModel - 1] // 根据操作切换url地址
      that.loading = true
      that.loadingSub = true
      let formData = that.$clone(that.form)
      let form = {
        ...formData,
        unitId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.id,
        careId: formData.care.key,
        preserverFileId: formData.preserverFile
          ? formData.preserverFile
              .map((item) => {
                return item.commonId
              })
              .toString()
          : '', //上传文件id的数组转字符串
        fileId: formData.fileList
          ? formData.fileList
              .map((item) => {
                return item.commonId
              })
              .toString()
          : '', //上传文件id的数组转字符串
        establishFileId: formData.fileTypeList
          ? formData.fileTypeList
              .map((item) => {
                return item.commonId
              })
              .toString()
          : '', //上传成立(更名)文件id的数组转字符串

        // sealStatusId: formData.sealStatus.key,
        orgId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.id,
        fileList: [],
        fileInfoVOS: [],
        preserverFile: []
      }
      api(form)
        .then(() => {
          that.loading = false
          that.$message.success('提交成功！')
          that.$multiTab.close()
        })
        .catch(() => {
          that.loading = false
        })
    }
  },
  mounted() {
    this.$route.meta.title = ['分公司印章状态查看', '分公司印章状态编辑', '分公司印章状态新增'][this.editModel]
    /**
     * 不为添加时请求详情
     * */
    if (this.editModel != 2) {
      this.loading = true
      detail(this.id)
        .then((res) => {
          this.loading = false

          this.$nextTick(() => {
            this.form = {
              ...res.data,
              fileList: res.data.fileInfoVOS,
              fileTypeList: res.data.establishFileInfoList,
              preserverFile: res.data.preserverFileInfoList,
              care: {
                key: res.data.careId,
                label: res.data.careName
              }

              // sealStatus:{
              //   key: res.data.sealStatusId,
              //   label: res.data.statusName,
              // }
            }
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.$nextTick(() => {
        this.init = true
      })
    }
  }
}
</script>

<style lang="less" scoped>
.file_prompt {
  color: #999;
}
</style>
